package com.bee.plus.ai.baidu;

import com.bee.plus.ai.baidu.vo.ResultRoot;
import com.bee.plus.ai.moonshot.vo.Choice;
import com.bee.plus.ai.moonshot.vo.KimiRootBean;
import com.bee.plus.dto.MessageReq;
import com.bee.plus.dto.MessageResp;
import com.bee.plus.util.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

/**
 * @author xupei
 */
public class HttpChatClient {

    private Logger logger= LoggerFactory.getLogger(HttpChatClient.class);

    private final String url;

    public HttpChatClient(String url) {
        this.url = url;
    }

    public void sendMessageAndGetResponse( MessageReq messageReq,ResponseCallback callback) throws IOException {
        String content = "";
        // Assuming the chat endpoint is at /chat
        String urlString = url;
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);

        String requestBody = JsonUtil.toJson(messageReq);
        connection.getOutputStream().write(requestBody.getBytes());

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                // Remove "data: " prefix
                line = line.replace("data: ", "");
                ResultRoot resultRoot = JsonUtil.fromJson(line, ResultRoot.class);
                logger.info("chat-message {}  {}",Thread.currentThread().getId(),line);
                if (resultRoot != null) {
                    content += resultRoot.getResult();
                }
                MessageResp messageResp = MessageResp.builder().content(content).role("assistant").build();
                callback.onResponse(messageResp);
            }
            MessageResp messageResp = MessageResp.builder().content(content).role("assistant").build();
            callback.finish(messageResp);
        } catch (IOException e) {
            e.printStackTrace();
            callback.onError(e);
        }


        connection.disconnect();
    }

    public void sendMessageAndGetResponseKimi(String authToken, MessageReq messageReq,ResponseCallback callback) throws IOException {
        String content = "";
        // Assuming the chat endpoint is at /chat
        String urlString = url;
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Authorization", "Bearer "+authToken);
        connection.setDoOutput(true);

        String requestBody = JsonUtil.toJson(messageReq);
        connection.getOutputStream().write(requestBody.getBytes());

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                // Remove "data: " prefix
               // logger.info("kimi-message-1 {}",line);
                line = line.replace("data: ", "");

                if(line.equals("[DONE]")){
                    break;
                }
                KimiRootBean resultRoot = JsonUtil.fromJson(line, KimiRootBean.class);
                if (resultRoot != null) {
                    List<Choice> list= resultRoot.getChoices();
                    for(Choice choice:list){
                        if(choice==null||choice.getDelta()==null|| StringUtils.isEmpty(choice.getDelta().getContent())){
                            continue;
                        }
                        content += choice.getDelta().getContent();
                    }
                }
                //logger.info("kimi-message-1 {}",content);
                MessageResp messageResp = MessageResp.builder().content(content).role("system").build();
                callback.onResponse(messageResp);
            }
            MessageResp messageResp = MessageResp.builder().content(content).role("system").build();
            callback.finish(messageResp);
        } catch (IOException e) {
            e.printStackTrace();
            callback.onError(e);
        }


        connection.disconnect();
    }
}
